package com.t194.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class LoginController {
    @GetMapping("/login")
    public String login() {
        return "login";
    }
    @PostMapping("/login")
    public String login(String userCode, String password) {
        UsernamePasswordToken token = new UsernamePasswordToken();
        System.out.println("用户名："+userCode+"密码："+password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        return "redirect:/index";
    }
    @ExceptionHandler(Exception.class)
    public String handleException(Exception ex, Model model) {
        System.out.println("处理异常");
        String error = "default";
        if (ex instanceof UnknownAccountException) {
            error =  "用户名或密码错误！";
        } else if(ex instanceof IncorrectCredentialsException) {
            error = "用户名或密码错误！";
        } else {
            error = "程序出错，请联系管理员！";
        }
        model.addAttribute("error", error);
        return "login";
   }
}
